import axios from 'axios'
import store from './store'
import router from './router'

//全局拦截
//token要放在请求header上面带会服务器

export default function setAxios () {
  //请求拦截  带上token
  axios.interceptors.request.use(
    config => {
      if (store.state.token) {
        config.headers.token = store.state.token
      }
      return config
    }
  )
  //响应拦截  确认登陆状态
  axios.interceptors.response.use(
    response => {
      if (response.status == 200) {
        const data = response.data
        if (data.code == -1) {
          store.commit('setToken', '')
          localStorage.removeItem('token')
          router.replace({ path: '/login' })
        }
        return data
      }
      return response
    }
  )
}